import React, {memo, useEffect, useState} from "react";
import useShortcutStore from "../store/shortcut";
import {
  Alert,
  Button,
  FlatList,
  SafeAreaView,
  ScrollView,
  StatusBar,
  Text,
  TouchableOpacity,
  useColorScheme,
  View
} from "react-native";
import {NavigationContainer} from "@react-navigation/native";
import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions
} from "react-native/Libraries/NewAppScreen";
import {GestureHandlerRootView, Swipeable} from "react-native-gesture-handler";
import RenderShortcut from "./RenderShortcut";

function Home(): React.JSX.Element {

  const shortcutStore = useShortcutStore();
  const shortcuts = shortcutStore.getShortcutList();
  const instanceUrl = "http://10.0.2.2:3000";
  const accessToken = "eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJuYW1lIjoiam9jdW5kX21vQGFsaXl1bi5jb20iLCJpc3MiOiJzbGFzaCIsInN1YiI6IjEwMiIsImF1ZCI6WyJ1c2VyLmFjY2Vzcy10b2tlbiJdLCJpYXQiOjE3MTM5MjE4OTZ9.KolIVA97gfDTXX1rx-rZe_nzFIo2MVxI5ggE3amH_-g";
  // const pageNumber = 1;
  const pageSize = 20;
  const selectedCollections = [];

  const [data, setData] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);
  const [loading, setLoading] = useState(false);
  const [buttonClicked, setButtonClicked] = useState<boolean>(false);

  const fetchData = async () => {
    setLoading(true);

    Promise.all([
      shortcutStore.fetchShortcutList(instanceUrl, accessToken, pageNumber, pageSize, selectedCollections),
      // shortcutStore.countShortcutList(selectedCollections, searchText, searchType),
    ])
      .then(([shortcuts]) => {
        setData(prevData => [...prevData, ...shortcuts]);
        setPageNumber(prevPage => prevPage + 1);
        console.log(shortcuts);
        console.log(shortcuts.length);
      }).catch((error) => {
      console.log(error.toString());
    })
      .finally(() => {
          setLoading(false);
      });
  };

  useEffect(() => {
    fetchData();
  }, []);

  const onPressButton = () => {
    Alert.alert('Button pressed!');
    setButtonClicked(prev => !prev);
    console.log(shortcuts.length);
    // Alert.alert(shortcuts.length);
  };
  // const handlePress = (item) => {
  //   console.log('Item pressed:', item);
  //   // 在这里可以处理列表项点击事件的逻辑
  // };
  // const handleDelete = (item) => {
  //   console.log('Delete item:', item);
  //   // 在这里可以处理删除操作的逻辑
  // };
  const handleEndReached = async () => {
    if (!loading) {
      await fetchData(); // 当用户滚动到列表底部时加载更多数据
    }
  };
  // const renderRightActions = (progress, dragX, item) => {
  //   const trans = dragX.interpolate({
  //     inputRange: [0, 50, 100],
  //     outputRange: [0, 0.2, 1],
  //   });
  //   return (
  //     <TouchableOpacity onPress={() => handleDelete(item)}>
  //       <View style={{ backgroundColor: 'red', justifyContent: 'center', alignItems: 'center', width: 100 }}>
  //         <Text style={{ color: 'white', paddingHorizontal: 10, paddingVertical: 15 }}>Delete</Text>
  //       </View>
  //     </TouchableOpacity>
  //   );
  // };

  // const renderShortcuts = memo(({ item }) => (
  //   <Swipeable renderRightActions={(progress, dragX) => renderRightActions(progress, dragX, item)}>
  //     <TouchableOpacity onPress={() => handlePress(item)} style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: '#ccc' }}>
  //       <Text>{item.title}</Text>
  //     </TouchableOpacity>
  //   </Swipeable>
  // ));
  // const renderShortcuts = ({ item }) => (
  //   <Swipeable renderRightActions={(progress, dragX) => renderRightActions(progress, dragX, item)}>
  //     <TouchableOpacity onPress={() => handlePress(item)} style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: '#ccc' }}>
  //       <Text>{item.title}</Text>
  //     </TouchableOpacity>
  //   </Swipeable>
  // );

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <Button
        title="Press me"
        onPress={onPressButton}
      />
      <FlatList data={data}
                keyExtractor={item => item.id}
                renderItem={({ item }) => (
                  <RenderShortcut
                    item={item}
                  />
                )}
                onEndReached={handleEndReached}
                onEndReachedThreshold={0.1}
      />
    </GestureHandlerRootView>
  );
}

export default Home;